package com.power.sifa.std.dao.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.plf.core.common.dao.OffersetTransformers;
import com.power.sifa.std.dao.Std_matter_attachDaoCustom;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.query.internal.NativeQueryImpl;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 申请所需材料 持久层实现(hibernate)
 */

@Repository
public class Std_matter_attachDaoImpl implements Std_matter_attachDaoCustom {

    @Resource
    private EntityManager entityManager;


    @Override
    @Transactional(readOnly = true)
    public List<Map<String, Object>> queryDossierMaterial(String applyid, List mattypeIds) {
        StringBuffer sql = new StringBuffer("select a.stdattachid, b.attachmentid, c.name, c.mattype, d.* from apl_matter_attach a left join apl_attachment b on a.id = b.matter_attachid left join std_attach c on a.stdattachid = c.id left join ha_attachment d on b.attachmentid = d.id where b.id is not null ");
        List<Object> params = new ArrayList<>();
        int index = 1;
        if (StringUtils.isNotEmpty(applyid)) {
            sql.append(" and a.applyid = ?" + index++);
            params.add(applyid);
        }
        if (CollectionUtil.isNotEmpty(mattypeIds)) {
            sql.append(" and c.mattype in ?" + index++);
            params.add(mattypeIds);
        }

        Query query = entityManager.createNativeQuery(sql.toString());
        query.unwrap(NativeQueryImpl.class).setResultTransformer(OffersetTransformers.ALIAS_TO_ENTITY_MAP);
        // 添加条件
        for (int i = 0; i <= params.size() - 1; i++) {
            query.setParameter(i + 1, params.get(i));
        }
        List<Map<String, Object>> result = query.getResultList();
        return result;
    }
}
